package shoppingmall.manage.interceptor;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import shoppingmall.manage.dto.Result;
import shoppingmall.manage.utils.JwtUtils;


@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override  //目标资源方法运行前运行，返回true:放行,返回false:不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("preHandle ...");

        //1.获取请求的url
        String url = request.getRequestURI().toString();
        log.info("请求的url:{}",url);

        //2.判断请求的url中是否包含login,如果包含，说明是登录操作，放行
        if(url.contains("login")){
            //log.info("登录操作，放行...");
            return true;
        }

        //3.获取请求头中的令牌(token)
        String jwt = request.getHeader("token");  //此处请求头中键为 ---> "token"

        //4.判断令牌是否存在，如果不存在，返回错误结果(未登录)
        if(!StringUtils.hasLength(jwt)){
            log.info("请求的token为空,返回未登录的信息");
            Result error = Result.error(401,"未经授权登录,token不存在!");
            //手动转换 对象--->json   阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(notLogin);
            return false;
        }

        //5.解析token,如果解析失败，返回错误结果(未登录)
        try {
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            //jwt解析失败
            e.printStackTrace();
            log.info("解析令牌失败，返回未登录错误信息");
            Result error = Result.error(401,"未经授权登录,token校验失败!");
            //手动转换 对象--->json   阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(notLogin);
            return false;
        }

        //6.令牌合法,放行
        log.info("令牌合法，放行");
        return true;
    }

    @Override  //目标资源运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("postHandle ...");
    }

    @Override  //视图渲染完毕后运行，最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //System.out.println("afterCompletion ...");
    }
}
